package com.xsmart.oa.services;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.oa.dao.AdminPowerSettingDAO;
import com.xsmart.oa.dao.QueryAdminManageDAO;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 *
 * @author lxh
 */
@Service
public class AdminPowerSettingService {

    @Autowired
    AdminPowerSettingDAO adminPowerSettingDAO;
    @Autowired
    QueryAdminManageDAO queryAdminManageDAO;
    /**
     * 所有权限内容和对应管理员信息
     * @param requestBean
     * @return
     */
    public ResponseBean queryAdminPowerList(RequestBean requestBean) {
        Integer currentPage = requestBean.getRequestParamInteger("currentPage", 1);
        Integer pageSize = requestBean.getRequestParamInteger("pageSize", 10);
        Integer userId=requestBean.getRequestParamInteger("userId");
        Integer actionType=requestBean.getRequestParamInteger("actionType");
        ResponseBean responseBean = requestBean.getResponseBean();
        Page<Map<String, Object>> page = new Page<>(currentPage, pageSize);
        List<Map<String,Object>> adminList=adminPowerSettingDAO.queryAdminPowerList(page,userId);
        //根据权限编码查询到对应的权限说明
        for(int i=0;i<adminList.size();i++){
            StringBuffer sb=new StringBuffer();
            Map<String,Object>adminListMap=adminList.get(i);
            String actionList=(String)adminListMap.get("action_list");
            List<String> actionListDesc=new ArrayList<String>();
            if(actionList!=null){
                String[]array=actionList.split(",");
                actionListDesc= queryAdminManageDAO.queryActionDesc(array);
            }
            for(int j=0;j<actionListDesc.size();j++){
                sb.append(actionListDesc.get(j)).append(',');
            }
            String actionDesc =sb.toString();
            if(actionDesc.length()>0){
                actionDesc=actionDesc.substring(0,actionDesc.length()-1);
            }
            adminListMap.put("action_list",actionDesc);
            adminList.set(i,adminListMap);
        }
        //查询管理员
        page.setRecords(adminList);
        //对应角色的所有权限
        // List<Map<String, Object>> actionDescs = adminPowerSettingDAO.queryActionDescs(actionType);
        responseBean.addResultPageItem("adminInfo", page);
        // responseBean.addResultItem("actionDescs", actionDescs);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 查询所有的权限列表
     * @param requestBean
     * @return
     */

    public ResponseBean queryAllPowerList(RequestBean requestBean){
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer currentPage = requestBean.getRequestParamInteger("currentPage", 1);
        Integer pageSize = requestBean.getRequestParamInteger("pageSize", 10);
        Integer actionType=requestBean.getRequestParamInteger("actionType");
        Integer userId=requestBean.getRequestParamInteger("userId");
        Integer id=requestBean.getRequestParamInteger("sellerId");
        String functionType=    requestBean.getRequestParamString("functionType");
        Page<Map<String, Object>> page = new Page<>(currentPage, pageSize);
        try{
            page.setRecords(adminPowerSettingDAO.queryActionDescs(page,actionType));
            if("GLYSJGLQXPZ".equals(functionType)){
                responseBean.addResultItem("actionList",adminPowerSettingDAO.queryActionIdByUserId2(userId,id));
            }else if("GLYPTQXPZ".equals(functionType)){
                responseBean.addResultItem("actionList",adminPowerSettingDAO.queryActionIdByUserId(userId));
            }
            getCfgsActionChildren(page.getRecords());
            responseBean.addResultPageItem("powerList",page);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }

    private void getCfgsActionChildren(List<Map<String, Object>> list) {
        getCfgsActionChildren(list, null);
    }

    /**
     * 获取子分类
     * @param list 分类
     * @param pcategory 父级节点
     */
    private void getCfgsActionChildren(List<Map<String, Object>> list, Map<String, Object> pcategory) {
        for (Map<String, Object> category : list) {
            if (pcategory != null && pcategory.containsKey("parent_node")) {
                category.put("parent_node", MapUtils.getString(pcategory, "parent_node", "") + "," + MapUtils.getString(category, "PARENT_ACTION_ID", ""));
            } else {
                category.put("parent_node", MapUtils.getString(category, "PARENT_ACTION_ID", ""));
            }

            List<Map<String, Object>> childrenList = adminPowerSettingDAO.queryCfgsAction(MapUtils.getLong(category, "ACTION_ID"));
            if (childrenList.size() > 0) {
                category.put("children", childrenList);
                getCfgsActionChildren(childrenList, category);
            }
        }
    }
    /**
     * 更新系统权限
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateAdminPower(RequestBean requestBean) {
        Integer userId = requestBean.getRequestParamInteger("user_id");
        Integer sellerId=requestBean.getRequestParamInteger("seller_id");
        String functionType=requestBean.getRequestParamString("functionType");
        Integer modUserId=requestBean.getRequestParamInteger("mod_user_id");
        //所赋予的权限
        List<Integer> actionList = (List<Integer>) requestBean.getRequestParam("actionList");
      //已经拥有的权限id
        List<Integer> actionIdList=new ArrayList<>();
        ResponseBean responseBean = requestBean.getResponseBean();
        if("GLYSJGLQXPZ".equals(functionType)){
                actionIdList = adminPowerSettingDAO.queryActionIdByUserId2(userId,sellerId);
        }else if("GLYPTQXPZ".equals(functionType)){
                actionIdList = adminPowerSettingDAO.queryActionIdByUserId(userId);
        }
        Collections.sort(actionList);
        String actionListStr = "";
        try{
            //需要删除的权限
            Collection<Integer> deleteList=new ArrayList<Integer>(actionIdList);
            //需要添加的权限
            Collection<Integer> addList=new ArrayList<Integer>(actionList);
            deleteList.removeAll(actionList);
            addList.removeAll(actionIdList);
            System.out.println("=======需要删除");
            System.out.println(deleteList);
            System.out.println("=======需要增加");
            System.out.println(addList);
            for (int i = 0; i < actionList.size(); i++) {
                Integer actionId = actionList.get(i);
                //查询对应权限的编码
                String actionCode = adminPowerSettingDAO.queryActionDescById(actionId);
                actionListStr += actionCode;
                if (i != actionList.size() - 1) {
                    actionListStr += ",";
                }
            }
            if (deleteList.size() != 0) {
                for (Integer actionId : deleteList) {
                    Map<String, Object> adminMap = new HashMap<String, Object>();
                    adminMap.put("userId", userId);
                    adminMap.put("actionId", actionId);
                    //删除该管理员所拥有的所有权限
                    adminPowerSettingDAO.deleteAdminPower(adminMap,sellerId,functionType);
                }
            }
            if(addList.size()!=0) {
                for (Integer actionId : addList) {
                    Map<String, Object> adminMap = new HashMap<String, Object>();
                    adminMap.put("userId", userId);
                    adminMap.put("actionId", actionId);
                    adminMap.put("modUserId", modUserId);
                    // 插入对应的权限表
                    adminPowerSettingDAO.insertAdminPower(adminMap, sellerId, functionType);
                }
            }
            //更新对应管理员所拥有的权限
            if("GLYPTQXPZ".equals(functionType)){
                adminPowerSettingDAO.updateAdminPower(actionListStr, userId);
            }
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }

    /**
     * 查询管理员可管理的商家
     * @param requestBean
     * @return
     */
    public ResponseBean queryAllSeller(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        Integer currentPage = requestBean.getRequestParamInteger("currentPage", 1);
        Integer pageSize = requestBean.getRequestParamInteger("pageSize", 10);
        Integer userId=requestBean.getRequestParamInteger("userId");
        Page<Map<String, Object>> page = new Page<>(currentPage, pageSize);
        try{
            page.setRecords(adminPowerSettingDAO.queryAllSeller(page,userId));
            responseBean.addResultPageItem("AllSeller",page);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }

        return responseBean;
    }
    /**
     * 查询所有的商家
     * @param requestBean
     * @return
     */

    public ResponseBean allSeller(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        Integer currentPage = requestBean.getRequestParamInteger("currentPage", 1);
        Integer pageSize = requestBean.getRequestParamInteger("pageSize", 10);
        //管理员id
        Integer id=requestBean.getRequestParamInteger("userId");
        //商店id
        Integer shopId=requestBean.getRequestParamInteger("shopId");
        //商店名称
        String shopName=requestBean.getRequestParamString("shopName");
        Page<Map<String, Object>> page = new Page<>(currentPage, pageSize);
        try{
            page.setRecords(adminPowerSettingDAO.allSeller(page,shopId,shopName));
            responseBean.addResultPageItem("SellerList",page);
            responseBean.addResultItem("sellerIdList",adminPowerSettingDAO.queryRelId(id));
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e) {
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }
    /**
     * 更新管理员可管理的商家
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateInfuAdminSellerRel(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        Integer userId=requestBean.getRequestParamInteger("userId");
        List<Integer> actionList = (List<Integer>) requestBean.getRequestParam("shopIdList");
        //删除原来有的商家
        try{
            adminPowerSettingDAO.deleteInfuAdminSeller(userId);
            if(actionList.size()!=0){
                for(Integer shopId:actionList){
                    //更新所管理的商家
                    adminPowerSettingDAO.insertInfuAdminSellerRel(shopId,userId);
                }
            }
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }
}
